import { otherRouter, appRouter } from '@/router/router'
import Util from '@/libs/util'
import user from './user'
import Vue from 'vue'

const app = {
  state: {
    userCurrentPermissions: [],
    indexSearch: [],
    cachePage: [],
    lang: '',
    isFullScreen: false,
    openedSubmenuArr: [], // 要展开的菜单数组
    menuTheme: 'dark', // 主题
    themeColor: '',
    pageOpenedList: [
      {
        title: '首页1',
        path: '',
        name: 'home_index'
      }
    ],
    currentPageName: '',
    currentPath: [
      {
        title: '首页1',
        path: '',
        name: 'home_index'
      }
    ], // 面包屑数组
    menuList: [],
    routers: [otherRouter, ...appRouter],
    tagsList: [...otherRouter.children],
    messageCount: 0,
    dontCache: ['text-editor', 'artical-publish'], // 在这里定义你不想要缓存的页面的name属性值(参见路由配置router.js)
    permission: {}, // 权限
    stores: [], // 门店
    willRefreshHome: {
      // 需要刷新的房源、房间信息
      // 在组件里通过watch 里面的homeId和roomId判断是否需要刷新
      homeId: '',
      roomId: ''
    }
  },
  getters: {
    userCurrentPermissions: state => state.userCurrentPermissions,
    canUseM3Remote: state => {
      return state.userCurrentPermissions.some(p => p.resource === 'access_control' && p.action === 'open')
    }
  },
  mutations: {
    setWillRefreshHome (state, home) {
      state.willRefreshHome = home
    },

    setTagsList (state, list) {
      state.tagsList.push(...list)
    },

    updateMenulist (state) {
      const permission = state.permission
      const menuList = []
      const isMigrateClient = user.state.isMigrateClient // 是否是2.0分账升级用户

      if (permission) {
        appRouter.forEach((item, index) => {
          const permissionMatched = item.children.filter(child => {
            // 2.0分账升级用户 只显示账户信息
            if (isMigrateClient && child.name === 'account_information') {
              return true
            }
            if (!isMigrateClient && child.permissionKey && permission[child.permissionKey]) {
              return true
            }
          })

          if (permissionMatched.length) {
            item.children = permissionMatched
            menuList.push(item)
          }
        })
      }
      state.menuList = menuList
    },
    changeMenuTheme (state, theme) {
      state.menuTheme = theme
    },
    changeMainTheme (state, mainTheme) {
      state.themeColor = mainTheme
    },
    addOpenSubmenu (state, name) {
      let hasThisName = false
      let isEmpty = false
      if (name.length === 0) {
        isEmpty = true
      }
      if (state.openedSubmenuArr.indexOf(name) > -1) {
        hasThisName = true
      }
      if (!hasThisName && !isEmpty) {
        state.openedSubmenuArr.push(name)
      }
    },
    closePage (state, name) {
      state.cachePage.forEach((item, index) => {
        if (item === name) {
          state.cachePage.splice(index, 1)
        }
      })
    },
    initCachepage (state) {
      if (localStorage.cachePage) {
        state.cachePage = JSON.parse(localStorage.cachePage)
      }
    },
    removeTag (state, name) {
      state.pageOpenedList.map((item, index) => {
        if (item.name === name) {
          state.pageOpenedList.splice(index, 1)
        }
      })
    },
    pageOpenedList (state, get) {
      let openedPage = state.pageOpenedList[get.index]
      if (get.argu) {
        openedPage.argu = get.argu
      }
      if (get.query) {
        openedPage.query = get.query
      }
      state.pageOpenedList.splice(get.index, 1, openedPage)
      localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList)
    },
    clearAllTags (state) {
      state.pageOpenedList.splice(1)
      state.cachePage.length = 0
      localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList)
    },
    clearOtherTags (state, vm) {
      let currentName = vm.$route.name
      let currentIndex = 0
      state.pageOpenedList.forEach((item, index) => {
        if (item.name === currentName) {
          currentIndex = index
        }
      })
      if (currentIndex === 0) {
        state.pageOpenedList.splice(1)
      } else {
        state.pageOpenedList.splice(currentIndex + 1)
        state.pageOpenedList.splice(1, currentIndex - 1)
      }
      let newCachepage = state.cachePage.filter(item => {
        return item === currentName
      })
      state.cachePage = newCachepage
      localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList)
    },
    setOpenedList (state) {
      state.pageOpenedList = localStorage.pageOpenedList ? JSON.parse(localStorage.pageOpenedList) : [otherRouter.children[0]]
    },
    setCurrentPath (state, pathArr) {
      state.currentPath = pathArr
    },
    setCurrentPageName (state, name) {
      state.currentPageName = name
    },
    setAvator (state, path) {
      localStorage.avatorImgPath = path
    },
    switchLang (state, lang) {
      state.lang = lang
      Vue.config.lang = lang
    },
    clearOpenedSubmenu (state) {
      state.openedSubmenuArr.length = 0
    },
    setMessageCount (state, count) {
      state.messageCount = count
    },
    increateTag (state, tagObj) {
      if (!Util.oneOf(tagObj.name, state.dontCache)) {
        state.cachePage.push(tagObj.name)
        localStorage.cachePage = JSON.stringify(state.cachePage)
      }
      state.pageOpenedList.push(tagObj)
      localStorage.pageOpenedList = JSON.stringify(state.pageOpenedList)
    },

    // 初始化权限列表
    // initPermissionList(state) {
    //     if (localStorage.permission) {
    //         state.permission = JSON.parse(localStorage.permission)
    //     }
    // },

    // 设置权限列表
    setPermissionList (state, pms) {
      if (!pms) {
        return
      }

      let list = []
      if (pms.permission_groups) {
        list = pms.permission_groups
      }

      // 额外权限
      let optPms = pms.client_optional_permissions

      if (optPms && optPms.length) {
        optPms.forEach(item => {
          item.key = 'opt_' + item.resource + '_' + item.action
        })

        list = list.concat(optPms)
      }

      if (!list.length) {
        return
      }

      state.userCurrentPermissions = list.reduce((result, group) => {
        if (group.permissions) {
          return result.concat(group.permissions.map(({id, action, resource, name}) => ({id, action, resource, name})))
        } else {
          return result.concat(group)
        }
      }, [])

      let map = { 'every': '首页' }
      list.forEach(item => {
        map[item.key] = item.name
      })
      state.permission = map
      // 设置菜单
      this.commit('updateMenulist')
      localStorage.permission = JSON.stringify(map)
    },

    // 初始化门店列表
    initStoreList (state) {
      if (localStorage.stores) {
        state.stores = JSON.parse(localStorage.stores)
      }
    },

    // 设置门店列表
    setStoreList (state, list) {
      if (!list || !list.length) {
        return
      }

      state.stores = list
      localStorage.stores = JSON.stringify(list)
    },

    // 初始化门店列表
    getStoreList (state) {
      return state.stores
    }
  }
}

export default app
